// import { chromium } from 'playwright'
import { chromium } from 'playwright-extra'
import stealth from 'puppeteer-extra-plugin-stealth'
import fs from 'fs-extra'

chromium.use(stealth())

// https://blog.csdn.net/m0_67790636/article/details/140611376
// const browser = await chromium.launch({
//   headless: false,
//   // 你本地谷歌浏览器的路径
//   executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',
//   userDataDir: 'C:/Users/llz/AppData/Local/Google/Chrome/User Data',
// })
// const browser = await chromium.connectOverCDP("http://localhost:9001");

class PlaywrightAPI {
  constructor() {}

  /**
   * @description
   *   Launch a new browser context and return it.
   *   The browser will be launched in non-headless mode, and the browser executable
   *   path will be set to the path of the Google Chrome browser on your system.
   *   The context will be launched with persistent storage enabled, and the storage
   *   state will be saved to the `./cache` directory.
   * @returns {Promise<import('playwright').BrowserContext>}
   */
  async getContext() {
    if (this.context) return this.context

    // await fs.copy('C:/Users/llz/AppData/Local/Google/Chrome/User Data', './data/cache')

    const context = await chromium.launchPersistentContext('./data/cache', {
      headless: false,

      // acceptDownloads: true, // 允许下载文件到缓存目录
      // permissions: ["geolocation"], // 持久化权限设置
      // storageState: "./auth.json", // 保存/加载登录状态
    })

    this.context = context

    return context
  }

  async getContext2() {
    // 如果已有上下文，直接返回
    if (this.context) {
      console.log('使用现有context')
      return this.context
    }

    console.log('重新getContext')

    try {
      // 启动浏览器

      await fs.copy('C:/Users/llz/AppData/Local/Google/Chrome/User Data', './temp-profile')

      const context = await chromium.launchPersistentContext(
        // 'C:/Users/llz/AppData/Local/Google/Chrome/User Data',
        './temp-profile',
        {
          headless: false, // 屋头模式
          executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',
        }
      )

      console.log('浏览器实例创建成功')

      this.context = context

      return context
    } catch (error) {
      console.error('创建浏览器上下文失败:', error)
      throw error // 或者根据你的需求处理错误
    }
  }
}

const api = new PlaywrightAPI()
api.getContext()

export default api
